<template>
	<!--  编辑弹框-->
	<el-dialog :model-value="dialogVisible" :show-close="false" :before-close="handleClose" width="35%">
		<template #header="{ titleId, titleClass }">
			<div class="my-header">
				<h4 :id="titleId" :class="titleClass">{{ headerTitle }}</h4>
				<el-button type="danger" plain size="small" class="custom-close-btn" @click="handleSilentClose">
					<el-icon :size="16"><Close /></el-icon>
				</el-button>
			</div>
		</template>
		<el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="120px" class="ruleForm" :size="formSize" status-icon>
			<el-form-item label="视频名称" prop="name">
				<el-input v-model="form.name" />
			</el-form-item>

			<el-form-item label="视频封面" prop="img">
				<UploadImage v-model="form.img" :file-size="5" :width="'150px'" :height="'150px'" :disabled="false" />
			</el-form-item>

			<el-form-item label="视频文件" prop="video">
				<el-upload
					ref="videoUploader"
					action=""
					:before-upload="uploadvideo"
					:show-file-list="false"
					drag
					:accept="'.mp4,.mov,.avi,.wmv,.flv,.mkv'"
					class="video-uploader"
				>
					<template v-if="!form.video">
						<div class="upload-content">
							<el-icon :size="60" class="upload-icon"><Upload /></el-icon>
							<div class="el-upload__text">
								将视频拖到此处或 <em>点击上传</em>
								<div class="el-upload__tip">支持格式：MP4/MOV/AVI/WMV/FLV/MKV，大小不超过100MB</div>
							</div>
						</div>
					</template>

					<template v-else>
						<div class="uploaded-file">
							<div class="action-buttons">
								<el-button type="primary" size="small" @click.stop="$refs.videoUploader.$el.querySelector('.el-upload__input').click()">
									修改
								</el-button>
								<el-button type="danger" size="small" @click.stop="form.video = ''"> 删除 </el-button>
							</div>
							<div class="preview-area" @click="dowload(form.video)">
								<div class="icon-wrapper">
									<el-icon class="file-icon"><VideoCameraFilled /></el-icon>
								</div>
							</div>
						</div>
					</template>
				</el-upload>
			</el-form-item>

			<el-form-item label="视频描述" prop="des">
				<el-input v-model="form.des" type="textarea" />
			</el-form-item>
		</el-form>
		<template #footer>
			<span class="dialog-footer">
				<el-button @click="handleResetForm(ruleFormRef)">取消</el-button>
				<el-button type="primary" @click="handleSubmitForm(ruleFormRef)"> 提交 </el-button>
			</span>
		</template>
	</el-dialog>

	<el-row style="width: 80%; margin: 0 auto; position: relative; top: 60px">
		<el-col>
			<el-form :inline="true">
				<el-row>
					<el-col>
						<el-form-item label-width="5px">
							<el-input v-model="name" placeholder="输入视频名称" />
						</el-form-item>

						<el-form-item label-width="5px">
							<el-radio-group v-model="statu" @change="load">
								<el-radio-button label="未审核" value="未审核"></el-radio-button>
								<el-radio-button label="未通过" value="未通过"></el-radio-button>
								<el-radio-button label="已通过" value="已通过"></el-radio-button>
							</el-radio-group>
						</el-form-item>
						<el-form-item label-width="5px">
							<el-button type="primary" :icon="Search" @click="load"> 查询 </el-button>
							<el-button type="warning" :icon="Refresh" @click="handleReset"> 重置 </el-button>
						</el-form-item>
					</el-col>
				</el-row>
			</el-form>
		</el-col>
		<el-col style="margin-bottom: 10px; display: flex; gap: 10px">
			<div>
				<el-button type="primary" :icon="Plus" size="small" plain @click="handleAdd"> 上传视频 </el-button>
			</div>
		</el-col>
		<el-col>
			<el-table
				:data="tableData"
				style="width: 100%"
				:header-cell-style="{ background: '#eef1f6', color: '#606266' }"
				@selection-change="handleSelectionChange"
			>
				<el-table-column prop="name" label="视频名称" align="center" show-overflow-tooltip />
				<el-table-column prop="img" label="视频封面" align="center">
					<template #default="scope">
						<el-image
							style="width: 50px; height: 50px"
							:src="scope.row.img"
							:preview-src-list="[scope.row.img]"
							:zoom-rate="1.2"
							:max-scale="7"
							:preview-teleported="true"
							:min-scale="0.2"
							:initial-index="0"
							fit="contain"
						/>
					</template>
				</el-table-column>
				<el-table-column prop="video" label="视频文件" align="center">
					<template #default="scope">
						<div class="play-icon-container" @click="dowload(scope.row.video)">
							<el-icon class="play-icon"><VideoPlay /></el-icon>
						</div>
					</template>
				</el-table-column>
				<el-table-column prop="des" label="视频描述" align="center" show-overflow-tooltip />

				<el-table-column prop="statu" label="当前状态" align="center">
					<template #default="scope">
						<el-tag>{{ scope.row.statu }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />

				<el-table-column label="操作" align="center" width="240">
					<template #default="scope">
						<div style="display: flex; justify-content: center; gap: 10px">
							<div>
								<el-button
									:type="scope.row.statu === '未审核' ? 'info' : 'success'"
									:icon="VideoPlay"
									size="small"
									:disabled="scope.row.statu === '未审核'"
									@click="scope.row.statu !== '未审核' && handleDetail(scope.row.id)"
								>
									详情
								</el-button>
							</div>
							<div>
								<el-button type="primary" :icon="Edit" size="small" @click="handleUpdate(scope.row.id)"> 编辑 </el-button>
							</div>
							<div>
								<el-popconfirm
									confirm-button-text="确定"
									cancel-button-text="取消"
									:icon="InfoFilled"
									icon-color="#626AEF"
									title="确认要删除吗？"
									@confirm="handleDel(scope.row.id)"
									@cancel="load"
								>
									<template #reference>
										<el-button type="danger" :icon="Delete" size="small"> 删除 </el-button>
									</template>
								</el-popconfirm>
							</div>
						</div>
					</template>
				</el-table-column>
			</el-table>
			<!--      分页按钮-->
			<div class="pagination">
				<el-pagination
					:current-page="pageNum"
					:page-size="pageSize"
					:page-sizes="[10, 20, 30, 50, 100, 500, 1000]"
					size="small"
					layout="total, sizes, prev, pager, next, jumper"
					:total="Number(total)"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
				/>
			</div>
		</el-col>
	</el-row>
</template>

<script setup>
import { reactive, ref } from 'vue'
import {
	CircleCloseFilled,
	Delete,
	Download,
	Edit,
	InfoFilled,
	Plus,
	Refresh,
	Search,
	Upload,
	VideoCameraFilled,
	VideoPlay
} from '@element-plus/icons-vue'
import request from '@/utils/request'
import { ElMessage, ElMessageBox } from 'element-plus'
import downloadExcel from '@/utils/downloads'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import UploadImage from '@/components/upload/upload-image/index.vue'
import router from '@/router'

const headerTitle = ref()
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)
const tableData = ref([])
const multipleSelection = ref([])
const disabled = ref(true)
const dialogVisible = ref(false)
const userList = ref([])
const name = ref('')
const uid = ref('')
const statu = ref('')
const formSize = ref('default')
const ruleFormRef = ref()
const $route = router

const form = reactive({
	id: undefined,
	name: undefined,
	img: undefined,
	video: undefined,
	des: undefined,
	click: 0,
	uid: undefined,
	statu: '未审核',
	createTime: undefined
})

// 表单校验规则
const rules = reactive({
	name: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	img: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	video: [{ required: true, message: '必选项不能为空', trigger: 'change' }],
	des: [{ required: true, message: '必选项不能为空', trigger: 'blur' }],
	uid: [{ required: true, message: '必选项不能为空', trigger: 'change' }]
})

// 前往播放视频
const handleDetail = async id => {
	$route.push(`/front/video/detail?id=${id}`)
}

//新增方法
const handleAdd = async () => {
	headerTitle.value = reactive('新增数据')
	dialogVisible.value = true
}

// 修改方法
const handleUpdate = async id => {
	dialogVisible.value = true
	headerTitle.value = reactive('编辑数据')
	const res = await request.get(`/video/${id}`)
	Object.assign(form, res.data)
	form.statu = '未审核'
}

// 单个删除方法
const handleDel = async id => {
	await request.delete(`/video/${id}`)
	ElMessage({
		showClose: true,
		message: '删除成功',
		type: 'success'
	})
	await load()
}
// 批量删除方法
const handleBatchDel = async () => {
	const ids = []
	multipleSelection.value.forEach(row => {
		ids.push(row.id)
	})
	await request.delete(`/video/batch/${ids}`)
	ElMessage({
		showClose: true,
		message: '批量删除成功',
		type: 'success'
	})
	await load()
}

// 分页查询方法（初始化方法，页面加载成功以后就调用的方法）
const load = async () => {
	const res = await request.get('/video/page', {
		params: {
			pageNum: pageNum.value,
			pageSize: pageSize.value,
			name: name.value,
			uid: uid.value,
			statu: statu.value
		}
	})
	pageNum.value = res.data.current
	pageSize.value = res.data.size
	total.value = res.data.total
	tableData.value = res.data.records
	//   userList
	const resuser = await request.get(`/user`)
	userList.value = resuser.data
}
// 加载页面初始化调用load方法
load()

// 清空查询数据重置方法
const handleReset = () => {
	name.value = ''
	uid.value = ''
	statu.value = ''
	load()
}
// 修改每页展示的数据量方法
const handleSizeChange = size => {
	pageSize.value = size
	load()
}
// 翻页方法
const handleCurrentChange = current => {
	pageNum.value = current
	load()
}
// 多选按钮处理方法
const handleSelectionChange = val => {
	multipleSelection.value = val
	disabled.value = val.length === 0
}

// 关闭弹框提示方法
const handleClose = done => {
	ElMessageBox.confirm('确定关闭窗口?')
		.then(() => {
			handleResetForm(ruleFormRef.value)
		})
		.then(() => {
			done()
		})
		.catch(() => {
			// catch error
		})
}

// 提交表单校验方法
const handleSubmitForm = async formEl => {
	if (!formEl) {
		return
	}

	await formEl.validate(async (valid, fields) => {
		if (valid) {
			await request({
				method: form.id ? 'put' : 'post',
				url: form.id ? `/video/${form.id}` : '/video',
				data: form
			})
			ElMessage({
				showClose: true,
				message: '操作成功',
				type: 'success'
			})
			await handleResetForm(formEl)
		} else {
			console.log('error submit!', fields)
		}
	})
}
// 批量导入读数据写到后端数据库中
const beforeBatchUpload = async file => {
	let fd = new FormData()
	fd.append('file', file)
	await request.post('/video/batch/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	await load()
}
// 批量导出方法
const handleBatchExport = async () => {
	const ids = multipleSelection.value.map(row => row.id)
	const res = await request(
		{
			url: `/video/batch/export/${ids}`,
			method: 'get',
			responseType: 'blob'
		} //在请求中加上这一行，特别重要
	)
	downloadExcel(res, '导出数据表')
}
// 取消弹框方法
const handleResetForm = async formEl => {
	if (!formEl) {
		return
	}
	formEl.resetFields()

	Object.assign(form, {
		id: undefined,
		name: undefined,
		img: undefined,
		video: undefined,
		des: undefined,
		uid: undefined,
		statu: '未审核',
		createTime: undefined
	})
	// formEl.clearValidate("img")
	dialogVisible.value = false
	await load()
}

const handleSilentClose = () => {
	handleResetForm(ruleFormRef.value)
	dialogVisible.value = false
}

// 文件上传方法
const uploadimg = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.img = res.data
	ruleFormRef.value.clearValidate('img')
}
const uploadvideo = async file => {
	let fd = new FormData()
	fd.append('file', file)
	const res = await request.post('/file/upload', fd, {
		headers: {
			'Content-Type': 'multipart/form-data'
		}
	})
	ElMessage({
		showClose: true,
		message: '上传成功',
		type: 'success'
	})
	form.video = res.data
	ruleFormRef.value.clearValidate('video')
}

// 文件下载
const dowload = async url => {
	window.open(url)
}
// 富文本文件上传
const onUploadImg = async (files, callback) => {
	let i = 0
	const res = await Promise.all(
		files.map(file => {
			if (i > 0) {
				return false
			}
			return new Promise((rev, rej) => {
				const formdata = new FormData()
				formdata.append('file', file)

				request
					.post('/file/upload', formdata, {
						headers: {
							'Content-Type': 'multipart/form-data'
						}
					})
					.then(res => {
						i++
						rev(res.data)
					})
					.catch(error => rej(error))
			})
		})
	)
	callback(res)
}
const change = async row => {
	await request.put(`/video/${row.id}`, row)
	ElMessage({
		showClose: true,
		message: '操作成功',
		type: 'success'
	})
	await load()
}
</script>

<style scoped lang="scss">
.el-form--inline .el-form-item {
	margin-right: 10px;
}

.form_header {
	background-color: #666666;
}

.pagination {
	margin-top: 10px;
}

.my-header {
	display: flex;
	flex-direction: row;
	justify-content: space-between;
}

.custom-close-btn {
	border: none !important;
	padding: 5px !important;
	transition: all 0.3s;

	&:hover {
		transform: rotate(90deg);
		color: #ff4d4f !important;
		background: rgba(255, 77, 79, 0.1) !important;
	}
}

.video-uploader {
	width: 100%;

	:deep(.el-upload) {
		width: 100%;

		.el-upload-dragger {
			width: 100%;
			padding: 20px;
			border-radius: 8px;
			background-color: #fafafa;
			transition: border-color 0.3s;

			&:hover {
				border-color: #409eff;
			}
		}
	}
}

.upload-content {
	display: flex;
	flex-direction: column;
	align-items: center;

	.upload-icon {
		margin-bottom: 10px;
		color: #c0c4cc;
	}

	.el-upload__text {
		text-align: center;

		em {
			color: #409eff;
			font-style: normal;
		}
	}

	.el-upload__tip {
		margin-top: 10px;
		font-size: 12px;
		color: #909399;
	}
}

.uploaded-file {
	position: relative;
	height: 180px;
	width: 100%;

	.action-buttons {
		position: absolute;
		top: 0px;
		right: 25px;
		display: flex;
		gap: 8px;
		z-index: 2;
		transform: translateX(30%);
	}

	.preview-area {
		height: 100%;
		width: 100%;
		display: flex;
		align-items: center;
		justify-content: center;
		cursor: pointer;
		padding: 20px;

		.icon-wrapper {
			display: flex;
			flex-direction: column;
			align-items: center;
			text-align: center;

			.file-icon {
				font-size: 60px;
				color: #409eff;
				margin-bottom: 8px;
			}

			.file-name {
				max-width: 80%;
				overflow: hidden;
				text-overflow: ellipsis;
				white-space: nowrap;
			}
		}
	}
}

.video-uploader :deep(.el-upload-dragger) {
	padding: 0;
}

.play-icon-container {
	display: inline-flex;
	align-items: center;
	justify-content: center;
	width: 32px;
	height: 32px;
	border-radius: 50%;
	background-color: #67c23a; /* Element UI success 颜色 */
	cursor: pointer;
	transition:
		background-color 0.3s ease,
		transform 0.2s ease;
}

.play-icon-container:hover {
	background-color: #5daf34; /* 悬停时稍深的绿色 */
	transform: scale(1.1);
}

.play-icon {
	color: white;
	font-size: 16px;
	margin-left: 2px; /* 微调图标位置 */
}
</style>
